package com.songcha.module_task.ui.fragment.task

import android.app.Application
import androidx.lifecycle.MutableLiveData
import com.songcha.library_base.interfaces.IApiResult
import com.songcha.library_base.mvvm.base.beanFlatMap
import com.songcha.library_business.api.ApiManager
import com.songcha.library_business.bean.advert.AdvertInfoBean
import com.songcha.library_business.bean.banner.BannerBean
import com.songcha.library_business.bean.user.UserInfoBean
import com.songcha.library_business.config.FunctionConfig
import com.songcha.library_business.config.VarConfig
import com.songcha.library_business.manager.TaskManager
import com.songcha.library_business.proxy.database.TodayObtainGoldCountDaoManager
import com.songcha.library_business.proxy.userinfo.UserInfoManager
import com.songcha.library_business.viewmodel.BaseErrorRefreshViewModel
import com.songcha.library_common.helper.SharedPreferenceHelper
import com.songcha.library_network.bean.BaseIntDataBean
import com.songcha.module_task.bean.DailyTaskBean
import com.songcha.module_task.bean.SignDayNumberBean
import com.songcha.module_task.bean.SignTaskBean
import com.songcha.module_task.ui.adapter.DailyTaskAdapter


class TaskViewModel(app: Application): BaseErrorRefreshViewModel<TaskRepository,String>(app){

    var signTaskList=MutableLiveData<MutableList<SignTaskBean.DataBean>>()
    //continuous sign day
    var signDay=MutableLiveData(0)
    var signState=MutableLiveData<Boolean>()
    var dailyTaskList=MutableLiveData<MutableList<DailyTaskBean.DataBean>>()
    var bannerList=MutableLiveData<MutableList<BannerBean.DataBean>>()
    var completeTaskState=MutableLiveData<Boolean>()

    override fun onHandleSuccess(bean: Any, isSetState: Boolean) {
        if(isSetState){
            onSetStateSuccess()
        }
    }

    fun getSignTask(){
        handleApiDataObserver(repository.getSignTask(),object :IApiResult<SignTaskBean>{
            override fun onSuccess(bean: SignTaskBean) {
                signTaskList.value = bean.data
            }

            override fun onError(e: Throwable) {

            }
        })
    }

    fun completeTask(idx:Int){
        if(dailyTaskList.value==null) return
        if(idx>dailyTaskList.value!!.size-1) return
        val taskId=dailyTaskList.value!![idx].id
        handleApiDataObserver(repository.completeTask(taskId),object :IApiResult<BaseIntDataBean>{
            override fun onSuccess(bean: BaseIntDataBean) {
                dailyTaskList.value!![idx].isAccomplish=true
                completeTaskState.value=true
                TodayObtainGoldCountDaoManager.addTodayObtainGoldCount(bean.data)
            }
        },false,false,false)
    }

    fun getUserSignDay(){
        if(!UserInfoManager.checkLogin()) return
        handleApiDataObserver(repository.getUserSignDay(),object:IApiResult<SignDayNumberBean>{
            override fun onSuccess(bean: SignDayNumberBean) {
                signDay.value=bean.data.continuousSigninNum
            }

        },true)
    }


    fun sign(position:Int){
        if(!UserInfoManager.checkJumpLogin()) return
        if(signTaskList.value==null) return
        if(position>signTaskList.value!!.size-1) return
        val awardGold = signTaskList.value!![position].awardGold

        val obs=repository.sign()
            .beanFlatMap{
                return@beanFlatMap ApiManager.api.getUserInfo()
            }.beanFlatMap{
                UserInfoManager.saveUserInfo(it.data)
                return@beanFlatMap repository.getUserSignDay()
            }

        handleApiDataObserver(obs,object :IApiResult<SignDayNumberBean>{
            override fun onSuccess(bean: SignDayNumberBean) {
                signDay.value=bean.data.continuousSigninNum
                signState.value=true
                TodayObtainGoldCountDaoManager.addTodayObtainGoldCount(awardGold)
            }

            override fun onError(e: Throwable) {
                signState.value=false
            }
        })

    }

    fun getUserInfo(){
        if(!UserInfoManager.checkLogin()) return
        handleApiDataObserver(repository.getUserInfo(), object : IApiResult<UserInfoBean> {
            override fun onSuccess(bean: UserInfoBean) {
                UserInfoManager.saveUserInfo(bean.data)
            }

            override fun onError(e: Throwable) {

            }
        },true)
    }

    fun getTaskBanner(){
        handleApiDataObserver(repository!!.getBanner(3), object : IApiResult<BannerBean> {
            override fun onSuccess(bean: BannerBean) {
                bannerList.value=bean.data
            }

            override fun onError(e: Throwable) {
                super.onError(e)
            }
        })
    }

    fun getDailyTask(){
        handleApiDataObserver(repository!!.getDailyTask(),object :IApiResult<DailyTaskBean>{
            override fun onSuccess(bean: DailyTaskBean) {
                val list = mutableListOf<DailyTaskBean.DataBean>()
                for(item in bean.data){
                    if(item.taskType == DailyTaskAdapter.TYPE_WATCH_REWARD_ADVERT){
                        if(item.norm == 1){
                            TaskManager.rewardTaskId = item.id
                        }else if(item.norm == 3){
                            TaskManager.reward3TaskId = item.id
                        }
                        if(FunctionConfig.IS_ADVERT_ENABLED && VarConfig.ADVERT_TASK_REWARD_INFO.type != AdvertInfoBean.ADVERT_TYPE_DIS_ENABLED)
                            list.add(item)
                    }else{
                        list.add(item)
                    }
                }
                dailyTaskList.value = list
                //dailyTaskList.value=bean.data
               /* ARouter.getInstance().build("/task/DailyTaskController").navigation()?.let {
                    (it as DailyTaskController).setTaskList(bean.data)
                }*/
            }

            override fun onError(e: Throwable) {

            }
        },true)
    }

    fun completeReaderRewardUnLoginTasks(){
        var rewardWatchCount = SharedPreferenceHelper.getInt("reader","reward_watch_count",0)
        if(rewardWatchCount == 0 || TaskManager.rewardTaskId == 0) return
        for(i in 0 until rewardWatchCount){
            handleApiDataObserver(repository.completeTask(TaskManager.rewardTaskId),object :IApiResult<BaseIntDataBean>{
                override fun onSuccess(bean: BaseIntDataBean) {
                    TodayObtainGoldCountDaoManager.addTodayObtainGoldCount(bean.data)
                    getUserInfo()
                }
            },false,false,false)
        }
        SharedPreferenceHelper.setInt("reader","reward_watch_count",0)
    }
}